package main

import (
	"fgo/advance/db/gorm/models"
	"github.com/google/martian/log"
	"github.com/jinzhu/gorm"
	"time"
)

func main() {
	log.SetLevel(log.Debug)
	db := models.NewDb()
	db.Callback().Update().Before("gorm:update").Register("gorm:update_limit_1", models.UpdateLimitOne)
	defer db.Close()

	//db.Create(&models.User{Name: "abc", Age: 20})
	////////////////// Update 更新单属性
	db.Model(&models.User{}).Where("age >= 10 AND age <= 20").Update("name", "张三")
	// UPDATE `user` SET `name` = '张三', `updated_at` = '2019-08-10 10:59:47'  WHERE (age >= 10 AND age <= 20)

	////////////////// Updates 更新多个字段
	// 注:Model 内仅仅支持设置主键
	db.Model(&models.User{Id: 1}).Updates(map[string]interface{}{"age": 22})
	// UPDATE `user` SET `age` = 22, `updated_at` = '2019-08-10 10:59:47'  WHERE `user`.`id` = 1

	// 更新: where 条件部分比较稳妥,如果使用模型,id一旦为0,则会更新整个数据库!!!!
	db.Model(&models.User{}).Where(map[string]interface{}{"id": 2}).Updates(map[string]interface{}{"age": 22})
	// UPDATE `user` SET `age` = 22, `updated_at` = '2019-08-10 11:01:52'  WHERE (`user`.`id` = 2)

	// 警告:当使用struct更新时，FORM将仅更新具有非空值的字段
	// 对于下面的更新，什么都不会更新为""，0，false是其类型的空白值
	db.Model(&models.User{}).Where("id = ?", 1).Updates(models.User{Name: "", Age: 0, UpdatedAt: time.Now()})
	// UPDATE `user` SET `created_at` = '2019-08-10 11:03:56', `updated_at` = '2019-08-10 11:03:56' WHERE (id = 1)

	////////////////// 执行原生 Sql
	db.Exec("UPDATE user SET age=? WHERE id IN (?)", 21, []int64{1, 2, 3})
	// UPDATE user SET age=21 WHERE id IN (1,2,3)

	////////////////// UpdateColumns 不会触发回调
	db.Model(&models.User{}).Where("id = ?", 1).Updates(models.User{Name: "hello", Age: 18})
	// UPDATE `user` SET `age` = 18, `name` = 'hello', `updated_at` = '2019-08-10 11:09:09'  WHERE (id = 1)
	db.Model(&models.User{}).Where("id = ?", 1).UpdateColumns(models.User{Name: "hello", Age: 18})
	// UPDATE `user` SET `age` = 18, `name` = 'hello'  WHERE (id = 1)

	//////////////////  使用SQL表达式更新
	db.Model(&models.User{}).Where("id = ?", 1).Update("age", gorm.Expr("`age`+?", 1))
	// UPDATE `user` SET `age` = `age`+1, `updated_at` = '2019-09-09 11:27:10'  WHERE (id = 1) LIMIT 1
}
